/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/Util/Error.h"
#include <WinSock2.h>

#define MSG_BUF_SIZE    0x200

namespace Shared {
namespace Util {

    static const char *getErrorMessage(int code, char* dest, std::size_t size)
    {
        char *s = NULL;
        FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER 
            | FORMAT_MESSAGE_FROM_SYSTEM 
            | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, code,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPSTR)&s, 0, NULL);
        _snprintf_s(dest, size, _TRUNCATE, "%s", s);
        LocalFree(s);
        return dest;
    }


    int lastError(void)
    {
        return GetLastError();
    }

    int lastNetError(void)
    {
        return WSAGetLastError();
    }

    const char *getErrorString(char *dest, std::size_t size, int ec /* = lastError */)
    {
        return getErrorMessage(ec, dest, size);
    }

    const char *getErrorString(::std::string &dest, int ec /* = lastError */)
    {
        char errmsg[MSG_BUF_SIZE];
        dest = getErrorMessage(ec, errmsg, sizeof(errmsg));
        return dest.c_str();
    }

    const ::std::string getErrorString(int ec /* = lastError */)
    {
        char errmsg[MSG_BUF_SIZE];
        getErrorMessage(ec, errmsg, sizeof(errmsg));
        return std::string(errmsg);
    }

}}